Home » SQL & PL/SQL » SQL & PL/SQL » Fine tuning a delete statement
Fine tuning a delete statement [message #48363] |
Tue, 16 November 2004 12:59  |
Leonard Martin
Messages: 45 Registered: May 2002 Location: Canada
|
Member |
|
|
Hello Oracle gurus
I have the following delete statement that would require to delete about
70,000 records. How could I fine tune this statement. If I use a cursor, how could
I frame the cursors to delete. The situation here is a NOT IN.
DELETE
����� FROM A
����� WHERE UNIQUE_ID NOT IN (SELECT unique_id FROM B WHERE filename='TEMP.DAT')
�
Thanks in advance
|
|
|
|
|
|
|
|
|
Re: Fine tuning a delete statement [message #48407 is a reply to message #48396] |
Thu, 18 November 2004 07:05  |
William Robertson
Messages: 1643 Registered: August 2003 Location: London, UK
|
Senior Member |
|
|
(Not sure what happened to my post above - looks fine in preview and on the test forum, so trying again...)
Yes, that should do it.
The problem with the earlier query arose if table B was (extreme example) empty. Leonard's original query,
DELETE FROM a
WHERE unique_id NOT IN
( SELECT unique_id
FROM b
WHERE filename='TEMP.DAT' );
would delete all rows from A, but
DELETE FROM a
WHERE EXISTS
( SELECT 1
FROM b
WHERE b.unique_id = a.unique_id
AND b.filename <> 'TEMP.DAT' );
or for that matter,
DELETE FROM a
WHERE unique_id IN
( SELECT unique_id
FROM b
WHERE filename <> 'TEMP.DAT' );
would delete nothing.
DELETE FROM a
WHERE NOT EXISTS
( SELECT 1
FROM b
WHERE b.unique_id = a.unique_id
AND b.filename = 'TEMP.DAT' );
is a valid variation on the original query. It might be faster, or slower, or come to the same thing, depending on data volumes, distribution, optimizer settings etc. See www.orafaq.com/msgboard/plsql/messages/19327.htm.
Actually now I think about it, NOT IN and NOT EXISTS are not be quite the same thing if b.unique_id can be null:
SQL> CREATE TABLE a AS SELECT rownum AS unique_id FROM user_objects;
Table created.
SQL> CREATE TABLE b AS SELECT unique_id, 'TEMP.DAT' AS filename FROM a;
Table created.
SQL> update b set unique_id = null where rownum = 1;
1 row updated.
SQL> SELECT unique_id FROM a
2 MINUS
3 SELECT unique_id FROM b;
UNIQUE_ID
----------
1
1 row selected.
SQL> commit;
Commit complete.
SQL> DELETE FROM a
1 WHERE unique_id NOT IN
2 ( SELECT unique_id
3 FROM b
4 WHERE filename='TEMP.DAT' );
<b>0 rows deleted.</b>
SQL> DELETE FROM a
2 WHERE NOT EXISTS
3 ( SELECT 1
4 FROM b
5 WHERE b.unique_id = a.unique_id
6* AND b.filename = 'TEMP.DAT' );
<b>1 row deleted.</b>
SQL> roll
Rollback complete.
SQL> DELETE FROM a
2 WHERE unique_id NOT IN
3 ( SELECT NVL(unique_id,-1)
4 FROM b
5* WHERE filename='TEMP.DAT' );
<b>1 row deleted.</b>
[Updated on: Fri, 18 February 2005 23:32] Report message to a moderator
|
|
|
Goto Forum:
Current Time: Fri Jun 20 05:43:02 CDT 2025
|